package org.vectrics.company.web.struts;

import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Category;
import org.apache.struts.action.ActionForm;
import org.vectrics.SystemException;
import org.vectrics.common.util.DateSync;
import org.vectrics.company.Company;
import org.vectrics.company.CompanyPerson;
import org.vectrics.company.CompanyPersonRole;
import org.vectrics.company.CompanyPersonRoleType;
import org.vectrics.provider.CoreServiceLocator;
import org.vectrics.struts.Request;
import org.vectrics.user.Person;


public class AddCompanyPersonAction extends RequestFormAction {
    private static Category log = Category.getInstance(AddCompanyPersonAction.class);
	public static String JOB_PARAM = "job";

	
	protected String fillForm(ActionForm formIn, Request request, HttpServletResponse response) {
		String mapCode = "success";

		log.info("Form type = " + formIn.getClass().getName());
		CompanyPersonForm form = (CompanyPersonForm)formIn;
		
		String companyIdParam = request.getParameter("companyId");
		String personIdParam = request.getParameter("personId");
	    Company company = CoreServiceLocator.getCompanyService().findCompany(new Long(companyIdParam));
	    Person person = CoreServiceLocator.getPersonService().findPersonById(new Long(personIdParam));
	    if (person == null) 
	    	throw new SystemException("Could not find person, id = " + personIdParam);
		CompanyPerson companyPerson = new CompanyPerson();
		companyPerson.setCompany(company);
		companyPerson.setPerson(person);
		companyPerson.setDateStart(DateSync.getCurrentTime());
		CompanyPersonRole newRole = new CompanyPersonRole();
		newRole.setDateStart(DateSync.getCurrentTime());
		CompanyPersonRoleType newRoleType = CoreServiceLocator.getCompanyService().findCompanyPersonRoleType("emp");
		newRole.setRoleType(newRoleType);
		newRole.setPerson(person);
		newRole.setTitle("Employee");
		companyPerson.addRole(newRole);
		newRole.setVoided(false);
		CoreServiceLocator.getCompanyService().updateCompanyPerson(companyPerson);

		form.setCompanyName(company.getName());
		form.setPersonName(person.getName());
		request.setAttribute("companyPersonId", companyPerson.getId().toString());			
		return(mapCode);
	}

	protected ActionForm createForm() {
	    log.info("createForm()");
		ActionForm form = new CompanyPersonForm();
		return(form);
	}
	
}
